package tool;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
/**
 * 
 * @author FJC
 * 编译
 */
public class AutoCompile {

	/**
	 * 编译Java文件
	 * @param filePath
	 * @throws IOException
	 */
	public void compile(String filePath) throws IOException {
		JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
		StandardJavaFileManager fileManager = compiler.getStandardFileManager(
				null, null, null);

		Iterable<? extends JavaFileObject> compilationUnits = fileManager
				.getJavaFileObjects(filePath);
		compiler.getTask(null, fileManager, null, null, null, compilationUnits)
				.call();

		fileManager.close();
	}
	/**
	 * 编译某一路径下的Java文件（不包含子目录内）
	 * @param filesPath
	 * @throws IOException
	 */
	private static void compileFiles(String filesPath) throws IOException {
		File dir = new File(filesPath);
		compileFiles(dir);
	}
	/**
	 * 编译某一路径下的Java文件（不包含子目录内）
	 * @param dir
	 * @throws IOException
	 */
	private static void compileFiles(File dir) throws IOException {
		JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
		StandardJavaFileManager fileManager = compiler.getStandardFileManager(
				null, null, null);
		Iterable<? extends JavaFileObject> compilationUnits = fileManager
				.getJavaFileObjects(dir.listFiles(new FileFilter(){
					@Override
					public boolean accept(File pathname) {
						if(pathname.getPath().endsWith(".java"))
							return true;
						return false;
					}					
				}));
		compiler.getTask(null, fileManager, null, null, null, compilationUnits)
				.call();
		fileManager.close();
	}
	
	public static void main(String[] args) throws IOException {
		compileFiles("src/tool");
	}
}